//
// Created by Hoyin on 2024/4/14.
//

#ifndef VISUAL_LOCATION_RAPIDJSONUTILS_H
#define VISUAL_LOCATION_RAPIDJSONUTILS_H

#include <iostream>
#include "rapidjson/document.h"

rapidjson::Value& getObjectFrom(rapidjson::Value &dom, const std::string &key) {
	if (dom.HasMember(key.c_str())) {
		return dom[key.c_str()];
	} else {
		std::cerr << "Could not find a key named " << key << std::endl;
		return dom;
	}
}

double getDoubleFrom(rapidjson::Value &dom, const std::string &key) {
	if (dom.HasMember(key.c_str())) {
		rapidjson::Value &node = dom[key.c_str()];
		if (node.IsDouble()) {
			return node.GetDouble();
		} else {
			std::cerr << "Type error in " << key << std::endl;
			return -1;
		}
	} else {
		std::cerr << "Could not find a key named " << key << std::endl;
		return -1;
	}
}

int getIntegerFrom(rapidjson::Value &dom, const std::string &key) {
	if (dom.HasMember(key.c_str())) {
		rapidjson::Value &node = dom[key.c_str()];
		if (node.IsInt()) {
			return node.GetInt();
		} else {
			std::cerr << "Type error in " << key << std::endl;
			return -1;
		}
	} else {
		std::cerr << "Could not find a key named " << key << std::endl;
		return -1;
	}
}

std::string getStringFrom(rapidjson::Value &dom, const std::string &key) {
	if (dom.HasMember(key.c_str())) {
		rapidjson::Value &node = dom[key.c_str()];
		if (node.IsString()) {
			return node.GetString();
		} else {
			std::cerr << "Type error in " << key << std::endl;
			return "";
		}
	} else {
		std::cerr << "Could not find a key named " << key << std::endl;
		return "";
	}
}

rapidjson::Document getDOM(const std::string &configFile) {
	rapidjson::Document dom;
	// 读取配置
	std::string configContent = utl::readFile(configFile).str();
	if (configContent == "failed") {
		std::cerr << "Failed to open config file at " << configFile << std::endl;
		return dom;
	}

	//  使用rapidjson解析
	dom.Parse(configContent.c_str());
	if (dom.HasParseError()) {
		std::cerr << "Rapidjson parse error." << std::endl;
	}
	return dom;
}
#endif //VISUAL_LOCATION_RAPIDJSONUTILS_H
